<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
    <title>耘享农场意向登记</title>
    <style>
        body { font-family: Arial, sans-serif; padding: 20px; background: #f5f5f5; }
        .form-container { max-width: 500px; margin: 0 auto; background: white; padding: 30px; border-radius: 8px; box-shadow: 0 2px 10px rgba(0,0,0,0.1); margin-bottom: 20px; }
        .query-container { max-width: 500px; margin: 0 auto; background: white; padding: 30px; border-radius: 8px; box-shadow: 0 2px 10px rgba(0,0,0,0.1); margin-bottom: 20px; }
        .results-container { max-width: 500px; margin: 0 auto; background: white; padding: 30px; border-radius: 8px; box-shadow: 0 2px 10px rgba(0,0,0,0.1); }
        input, textarea, button, select { width: 100%; padding: 10px; margin: 10px 0; border: 1px solid #ddd; border-radius: 4px; box-sizing: border-box; }
        button { background-color: #409eff; color: white; border: none; cursor: pointer; }
        button:hover { background-color: #307ecc; }
        h2 { text-align: center; color: #333; }
        h3 { text-align: center; color: #333; margin-top: 0; }
        .result-item { border: 1px solid #eee; padding: 15px; margin-bottom: 10px; border-radius: 4px; display: flex; align-items: center; justify-content: space-between; }
        .item-checkbox { margin-left: 10px; }
        .address-content { display: flex; align-items: center; white-space: nowrap; }
.address-label { margin-right: 5px; white-space: nowrap; }
.address-value { white-space: nowrap; overflow: hidden; text-overflow: ellipsis; flex: 1; }
        .result-item-content div { margin-bottom: 5px; }
        .batch-actions { margin-bottom: 15px; display: flex; align-items: center; justify-content: space-between; }
        .batch-actions label { display: flex; align-items: center; white-space: nowrap; }
        .batch-actions input[type="checkbox"] { margin-right: 5px; width: auto; }
        .batch-delete-btn { background-color: #f56c6c; padding: 5px 15px; border: none; border-radius: 4px; color: white; cursor: pointer; width: auto; }
        .batch-delete-btn:hover { background-color: #f78989; }
        .batch-delete-btn:disabled { background-color: #dcdfe6; cursor: not-allowed; }
        .no-results { text-align: center; color: #999; padding: 20px; }
        .query-btn { background-color: #67c23a; }
        .query-btn:hover { background-color: #5daf34; }
    </style>
</head>
<body>
<div class="form-container">
    <h2>耘享农场意向登记</h2>
    <form id="infoForm">
        <input type="text" id="name" placeholder="姓名" required />
        <input type="tel" id="phone" placeholder="手机号" required />
        <select id="gender" required>
            <option value="">选择性别</option>
            <option value="1">先生</option>
            <option value="2">女士</option>
        </select>

        <!-- 替换为下拉选择框 -->
        <select id="addressNo" required>
            <option value="">请选择意向地址</option>
            <!-- 选项由 JS 动态生成 -->
        </select>

        <textarea id="remark" placeholder="备注（最多不能超过900字符）"></textarea>
        <button type="submit">提交信息</button>
    </form>
</div>

<div class="query-container">
    <h3>查询我的意向记录</h3>
    <div id="queryForm">
        <input type="tel" id="queryPhone" placeholder="请输入手机号查询" required />
        <button type="button" id="queryBtn" class="query-btn">查询记录</button>
    </div>
</div>

<div class="results-container" style="display: none;">
    <h3>我的意向记录</h3>
    <div class="batch-actions">
        <label>
            <input type="checkbox" id="selectAll"> 全选
        </label>
        <button type="button" id="batchDeleteBtn" class="batch-delete-btn" disabled>批量删除</button>
    </div>
    <div id="resultsList"></div>
</div>

<script>
    // 页面加载完成后生成地址选项
    document.addEventListener('DOMContentLoaded', function () {
        const select = document.getElementById('addressNo');

        // 生成 a, b, c 三个区域，每个区域 1 到 100 号
        ['a'].forEach(area => {
            for (let i = 1; i <= 100; i++) {
                const option = document.createElement('option');
                option.value = `${area}${i}`;
                option.textContent = `${area.toUpperCase()}${i}`;
                select.appendChild(option);
            }
        });
    });

    // 表单提交处理
    document.getElementById('infoForm').addEventListener('submit', async function(e) {
        e.preventDefault();

        const name = document.getElementById('name').value.trim();
        const phone = document.getElementById('phone').value.trim();
        const gender = document.getElementById('gender').value;
        const addressNo = document.getElementById('addressNo').value;
        const remark = document.getElementById('remark').value.trim();

        // 构造符合目标接口的请求体
        const payload = {
            userName: name,
            gender: gender,
            userPhoneNumber: phone,
            remark: remark,
            intentionAddressNo: addressNo
        };

        try {
            const res = await fetch('http://1.15.178.98:8080/customer/intention/add', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'tenant-id': '2'
                },
                body: JSON.stringify(payload)
            });

            const result = await res.json();

            if (result.code === 200) {
                alert('操作成功');
                document.getElementById('infoForm').reset(); // 清空表单
            } else {
                alert(result.msg || '提交失败，请重试');
            }
        } catch (err) {
            console.error('网络请求错误：', err);
        }
    });

    // 查询我的意向记录
    document.getElementById('queryBtn').addEventListener('click', async function() {
        const phone = document.getElementById('queryPhone').value.trim();
        
        if (!phone) {
            alert('请输入手机号');
            return;
        }

        try {
            // 构造查询URL，使用GET请求
            const queryUrl = `http://1.15.178.98:8080/customer/intention/find?userPhoneNumber=${encodeURIComponent(phone)}`;
            
            const res = await fetch(queryUrl, {
                method: 'GET',
                headers: {
                    'Content-Type': 'application/json'
                }
            });

            const result = await res.json();

            // 显示结果容器
            const resultsContainer = document.querySelector('.results-container');
            resultsContainer.style.display = 'block';
            
            // 清空之前的结果
            const resultsList = document.getElementById('resultsList');
            resultsList.innerHTML = '';
            
            // 重置全选复选框
            document.getElementById('selectAll').checked = false;
            // 重置批量删除按钮状态
            updateBatchDeleteButton();

            if (result.code === 200 && Array.isArray(result.data) && result.data.length > 0) {
                // 遍历结果列表，创建显示项
                result.data.forEach(item => {
                    const resultItem = document.createElement('div');
                    resultItem.className = 'result-item';
                    
                    // 格式化数据显示
                    let content = `<div class="address-content">
                                <span class="address-label">意向地址:</span>
                                <span class="address-value">${item.intentionAddressNo || '未选择'}</span>
                            </div>
                            <input type="checkbox" class="item-checkbox" data-id="${item.id}">`;
                    
                    resultItem.innerHTML = content;
                    resultsList.appendChild(resultItem);
                    
                    // 复选框的点击事件将在循环结束后统一绑定
                });

                // 使用事件委托为所有复选框绑定点击事件
                resultsList.addEventListener('change', function(e) {
                    if (e.target.classList.contains('item-checkbox')) {
                        updateBatchDeleteButton();
                    }
                });
            } else {
                // 无结果时显示提示
                resultsList.innerHTML = '<div class="no-results">暂无相关意向记录</div>';
            }
        } catch (err) {
            console.error('查询请求错误：', err);
            alert('查询失败，请重试');
        }
    });

    // 更新批量删除按钮状态
    function updateBatchDeleteButton() {
        const checkedItems = document.querySelectorAll('.item-checkbox:checked');
        const batchDeleteBtn = document.getElementById('batchDeleteBtn');
        batchDeleteBtn.disabled = checkedItems.length === 0;
        
        // 更新全选状态
        const allItems = document.querySelectorAll('.item-checkbox');
        const selectAll = document.getElementById('selectAll');
        selectAll.checked = allItems.length > 0 && allItems.length === checkedItems.length;
    }

    // 全选功能
    document.getElementById('selectAll').addEventListener('change', function() {
        const isChecked = this.checked;
        const allItems = document.querySelectorAll('.item-checkbox');
        allItems.forEach(item => {
            item.checked = isChecked;
        });
        updateBatchDeleteButton();
    });

    // 批量删除功能
    document.getElementById('batchDeleteBtn').addEventListener('click', async function() {
        const checkedItems = document.querySelectorAll('.item-checkbox:checked');
        if (checkedItems.length === 0) {
            alert('请选择要删除的记录');
            return;
        }
        
        // 获取选中的ID列表
        const ids = Array.from(checkedItems).map(item => item.getAttribute('data-id'));
        
        if (confirm(`确定要删除选中的 ${ids.length} 条记录吗？`)) {
            try {
                // 构造批量删除URL，使用DELETE请求
                const deleteUrl = `http://1.15.178.98:8080/customer/intention/delete/${ids.join(',')}`;
                
                const res = await fetch(deleteUrl, {
                    method: 'DELETE',
                    headers: {
                        'Content-Type': 'application/json'
                    }
                });
                
                const result = await res.json();
                
                if (result.code === 200) {
                    alert('删除成功');
                    // 删除成功后重新查询数据
                    document.getElementById('queryBtn').click();
                } else {
                    alert(result.msg || '删除失败，请重试');
                }
            } catch (err) {
                console.error('删除请求错误：', err);
                alert('删除失败，请重试');
            }
        }
    });
</script>
</body>
</html>